package com.qbd.show.utils;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class Tools {

    /**
     * 获取实体类表名称
     * @param c 表名称
     * @return
     */
    public String getTableClass(Class c){
        Table tableName = (Table)c.getAnnotation(Table.class);
        return tableName.name();
    }

    /**
     * 获取实体类中带有@Cloumn字段名称
     * @param clazz
     * @return
     */
    public List<String> getAllColumns(Class<?> clazz) {
        List<String> columns = new ArrayList<String>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            columns.add(StringUtils.camelToUnderline(field.getName()));
        }
        return columns;
    }

    /**
     * 通过获取类上的@Table注解获取表名称
     *
     * @param clazz
     * @return
     */
    public Map<String, String> getTableName(Class<?> clazz) {
        Map<String, String> map = new ConcurrentHashMap<>();
        Table annotation = clazz.getAnnotation(Table.class);
        String name = annotation.name();
        String className = clazz.getSimpleName();
        map.put("tableName", name);
        map.put("className", className);
        return map;
    }
}
